//
//  HMWriteToView.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/21.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit
import pop

class HMWriteToView: UIView {
    
    lazy var buttonArray: [HMComposeButton] = [HMComposeButton]()
    
    //展现撰写视图
    func show(fromVC: UIViewController?) {
        //将当前的视图添加到window上/根视图控制器的view上/传递控制器
        fromVC?.view.addSubview(self)
        //开始动画
        for (index,btn) in buttonArray.enumerated() {
            self.startAnimation(btn: btn, index: index)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
//        self.backgroundColor = 
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 触摸事件
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for (index,btn) in buttonArray.reversed().enumerated() {
            self.startAnimation(btn: btn, index: index,isShow: false)
        }
        
        //动画执行完毕之后 移除视图
        //延迟移除
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
            self.removeFromSuperview()
        })
        
    }
    
    //开始撰写按钮的动画效果
    private func startAnimation(btn: HMComposeButton,index: Int, isShow: Bool = true) {
        
        //添加动画对象
        let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //设置属性
        springAnimation?.springBounciness = 10.0
        springAnimation?.springSpeed = 10
        //设置延迟时间
        springAnimation?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        let btnCenterY = btn.center.y + CGFloat(isShow ? -350 : 350)
        springAnimation?.toValue = NSValue.init(cgPoint: CGPoint(x: btn.center.x, y: btnCenterY))
        btn.pop_add(springAnimation, forKey: nil)
        
    }
    
    @objc private func composeBtnDidClick(btn: HMComposeButton) {
        //1.被点击的按钮执行放大 其他按钮执行缩小   -> 修改transform
        UIView.animate(withDuration: 0.5, animations: {
            //遍历数组 获取按钮
            for composeBtn in self.buttonArray {
                if btn == composeBtn {
                    //就是被点击的按钮 放大\
                    composeBtn.transform = CGAffineTransform.init(scaleX: 2, y: 2)
                } else {
                    //其他按钮 缩小
                    composeBtn.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2)
                    //修改alpha
                    composeBtn.alpha = 0.1
                }
            }
        }, completion: { (_) -> () in
            //2.跳转对应的控制器
            //通过网络数据已经解析了一个控制器名称的字符串
            let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as! String
            let className = bundleName + "." + "HMComposeViewController"
            //1. 获取类型
            guard let classType = NSClassFromString(className) as? UIViewController.Type else {
                return
            }
            
            //2.根据类型实例化控制器对象
            let vc = classType.init()
            //实例化导航视图控制器
            let nav = UINavigationController(rootViewController: vc)
            //present 和 dismiss 并不是马上就完成
            UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: {
                //但是 跳转完控制器之后希望立即执行一些操作的时候
                self.removeFromSuperview()
            })
            
        })
    }
    
    private func setupUI() {
        //添加被处理毛玻璃效果的背景视图  截取屏幕
        let toolBar = UIToolbar(frame: UIScreen.main.bounds)
        toolBar.barStyle = .default
        self.addSubview(backView)
        self.addSubview(toolBar)
        self.addSubview(slogonView)
        //设置约束
        slogonView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addComposeButtons()
    }
    
    //添加撰写按钮
    private func addComposeButtons() {
        let btnMargin = (ScreenWidth - 3 * composeBtnImageWidth) / 4
        
        for i in 0..<6 {
            let btn = HMComposeButton()
            //应该确定对应的列的索引
            //确定列
            let coloumIndex = i % 3
            //确定行
            let rowIndex = i / 3
            //计算 x
            let btnX = btnMargin + (composeBtnImageWidth + btnMargin) * CGFloat(coloumIndex)
            //计算 y
            let btnY = (composeBtnHeight + btnMargin) * CGFloat(rowIndex) + ScreenHeight
            btn.setImage(#imageLiteral(resourceName: "tabbar_compose_friend"), for: .normal)
            btn.setTitle("💖", for: .normal)
            btn.frame = CGRect(x: btnX, y: btnY, width: composeBtnImageWidth, height: composeBtnHeight)
            self.addSubview(btn)
            buttonArray.append(btn)
            //监听按钮的点击事件
            btn.addTarget(self, action: #selector(composeBtnDidClick(btn:)), for: .touchUpInside)
        }
    }
        
    private lazy var backView: UIImageView = UIImageView(image: UIImage.snapShotCurrentWindow())
    
    private lazy var slogonView: UIImageView = UIImageView(image:#imageLiteral(resourceName: "compose_slogan"))
    
    
}
